<?php
namespace App\DBs;

use Illuminate\Support\Facades\DB;

class StuffDB extends BaseDB
{
    /**
     * 素材
     */

    protected $tStuff = 'stuff';

    public function __construct()
    {
    }

    /**
     * APP视频素材
     */
    public function getAppIndex($page,$size,$stamp,$type)
    {
        $models = DB::table($this->tStuff)->where('del',0)->where('stamp',$stamp)
            ->where('type',$type)->orderBy('id','desc')
            ->skip($page)->take($size)->get();
        if (!count($models)) { return array('code'=>'-1','msg'=>'no data'); }
        $models = $this->jsonToArr($models);
        $items = array();
        foreach ($models as $model) {
            $cover = file_exists($model['cover']) ? $model['cover'] : '';
            $link = file_exists($model['link']) ? $model['link'] : '';
            $items[] = [
                'id'=>$model['id'], 'type'=>$model['type'],
                'cover'=>$cover, 'link'=>$link, 'dn'=>env('DOMAIN').'/',
            ];
        }
        return array('code'=>'0','msg'=>'success','data'=>$items);
    }

    /**
     * APP新增文件
     */
    public function setAppAdd($stamp,$type,$cover='',$link='')
    {
        //开启事务
        DB::beginTransaction();
        try {
            $lastId = DB::table($this->tStuff)->insertGetId([
                'stamp'=>$stamp, 'type'=>$type,
                'cover'=>$cover, 'link'=>$link, 'created_at'=>time(),
            ]);
            if (!$lastId) { return array('code'=>'-2', 'msg'=>'新增失败'); }
            //提交事务
            DB::commit();
            return array('code'=>'0', 'msg'=>'操作成功', 'data'=>$lastId);
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>'-1', 'msg'=>'操作失败：'.$e);
        }
    }
}